package com.wangshuo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wangshuo.common.JwtHelper;
import com.wangshuo.config.Result;
import com.wangshuo.entity.Address;
import com.wangshuo.service.AddressService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Resource
    private AddressService addressService;
@Resource
private JwtHelper jwtHelper;
    @GetMapping("/list")
    public Result list(@RequestParam Integer pageNum, @RequestParam Integer pageSize, HttpServletRequest httpServletRequest){
        Long uid = jwtHelper.getUserId(httpServletRequest.getHeader("token"));

        IPage<Address> page=new Page<>(pageNum,pageSize);
        IPage<Address> list=addressService.getlist(page,uid);
        return Result.ok(list);

    }
    @PostMapping("/add")
    public Result add(@RequestBody Address address,HttpServletRequest httpServletRequest){
        Long uid = jwtHelper.getUserId(httpServletRequest.getHeader("token"));
address.setUid(Math.toIntExact(uid));
        addressService.saveOrUpdate(address);
        return Result.ok("成功");
    }
    @GetMapping("/delete")
    public Result delete(@RequestParam Long id){
        addressService.removeById(id);
        return Result.ok("成功");
    }
    @GetMapping("/all")
    public Result all(HttpServletRequest httpServletRequest){
        Long uid = jwtHelper.getUserId(httpServletRequest.getHeader("token"));
        LambdaQueryWrapper<Address> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Address::getUid,uid);
        List<Address> list=addressService.list(lambdaQueryWrapper);
        return Result.ok(list);
    }

}
